package top.codedance.iotp.server.net.handle.util;

import top.codedance.iotp.common.entity.CommonEntity;
import cd.io.netty.channel.Channel;
import top.codedance.iotp.server.ServerApplication;
import org.apache.log4j.Logger;

import java.util.concurrent.ConcurrentHashMap;

public class AsyncRequestServiceImpl implements AsyncRequestService {
    private Logger logger = ServerApplication.getLogger(AsyncRequestServiceImpl.class);

    private static ConcurrentHashMap<String, SyncFuture> futureCache = new ConcurrentHashMap();

    public void sendMsg(Channel channel, CommonEntity commonEntity) {
        SyncFuture<CommonEntity> syncFuture = new SyncFuture<>();
        // 放入缓存中
        futureCache.put(getKey(commonEntity), syncFuture);
        channel.writeAndFlush(commonEntity.build());
    }

    public void ackMsg(CommonEntity commonEntity) {
        // 从缓存中获取数据
        SyncFuture<CommonEntity> syncFuture = futureCache.get(getKey(commonEntity));
        // 如果不为null, 则通知返回
        if(syncFuture == null) {
            syncFuture = new SyncFuture<>();
        }
        syncFuture.setResponse(commonEntity);
        futureCache.put(getKey(commonEntity), syncFuture);
    }

    @Override
    public CommonEntity monitorMsg(CommonEntity commonEntity) {
        CommonEntity result = null;
        SyncFuture<CommonEntity> syncFuture = futureCache.get(getKey(commonEntity));
        if(syncFuture != null) {
            try {
                result = syncFuture.get();
            } catch (InterruptedException e) {
                logger.debug(e.getMessage());
            }
            futureCache.remove(getKey(commonEntity));
        }
        return result;
    }

    private String getKey(CommonEntity commonEntity){
        return String.valueOf(commonEntity.getVersion());
    }
}
